package com.book.breakage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.book.breakage.entity.Back;
import com.book.breakage.service.BackService;
import com.book.business.entity.BookIndent;
import com.book.business.entity.BookSell;
import com.book.business.service.BookIndentService;
import com.book.business.service.BookSellService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.common.utils.WareBook;
import com.book.publishing.entity.Bookman;
import com.book.publishing.service.BookmanService;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.stat.entity.BreakageStat;
import com.book.stat.service.BreakageStatService;
import com.book.system.entity.Money;
import com.book.system.entity.User;
import com.book.system.service.IUserService;
import com.book.system.service.MoneyService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.service.WarehouseBookService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: 张高赫
 * @Description: 20173954
 */

@Controller
public class BackController extends BaseController {
    @Autowired
    BackService backService;
    @Autowired
    BreakageStatService breakageStatService;
    @Autowired
    BookIndentService bookIndentService;
    @Autowired
    BookSellService bookSellService;
    @Autowired
    MoneyService moneyService;
    @Autowired
    IUserService userService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    WarehouseBookService warehouseBookService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/back")
    public String breReturnIndex() {
        return FebsUtil.view("breakage/back/backList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/back/add")
    public String backAdd() {
        return FebsUtil.view("breakage/back/backAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/back/update/{id}")
    public String backUpdate(@PathVariable Integer id, ModelMap modelMap) {
        Back back = backService.getById(id);
        modelMap.addAttribute("back", back);
        return FebsUtil.view("breakage/back/backUpdate");
    }

    @GetMapping("back")
    @ResponseBody
    @RequiresPermissions("back:view")
    public FebsResponse findBack(Back back) {
        return new FebsResponse().success().data(backService.backList(back));
    }

    @Log("访问退书报损")
    @GetMapping("back/list")
    @ResponseBody
    @RequiresPermissions("back:view")
    public FebsResponse backList(QueryRequest request, Back back) {
        Map<String, Object> dataTable = getDataTable(this.backService.backPage(request, back));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("退书报损-修改")
    @PostMapping("back/update")
    @ResponseBody
    @RequiresPermissions("back:update")
    @ControllerEndpoint(operation = "修改报损信息成功", exceptionMessage = "修改报损信息失败")
    public FebsResponse backUpdate(Back back) {
        this.backService.backUpdate(back);
        return new FebsResponse().success();
    }

    @Log("退书报损-删除")
    @PostMapping("back/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("back:delete")
    @ControllerEndpoint(operation = "删除报损成功", exceptionMessage = "删除报损信息失败")
    public FebsResponse backDelete(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Back> backList = backService.backApply(arr);
        for (int i = 0; i < backList.size(); i++) {
            if ("0".equals(backList.get(i).getStatus())) {
                return new FebsResponse().message("退书信息还未进行审批，不能删除！");
            }
            this.backService.backDelete(arr);
        }
        return new FebsResponse().success();
    }

    @Log("退书报损-审批")
    @PostMapping("back/apply/{ids}")
    @ResponseBody
    @RequiresPermissions("back:apply")
    @ControllerEndpoint(operation = "退书审批成功", exceptionMessage = "退书审批失败")
    public FebsResponse backApply(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Back> backList = backService.backApply(arr);
        for (int i = 0; i < backList.size(); i++) {
            if ("1".equals(backList.get(i).getStatus())) {
                return new FebsResponse().message("该条报损信息已经审批，请勿重复审批！");
            }
            if ("2".equals(backList.get(i).getStatus())) {
                return new FebsResponse().message("该报损信息已经驳回，不能再进行审批！");
            }
            BookIndent bookIndent = bookIndentService.getById(backList.get(i).getIndentid());
            breakageStatService.update(new UpdateWrapper<BreakageStat>().lambda()
                    .eq(BreakageStat::getBreakageid, backList.get(i).getIndentid()).set(true, BreakageStat::getOmit, "1"));
            //拿到资费信息里的数据
            Money money = moneyService.getOne(new QueryWrapper<Money>().lambda().eq(Money::getBookindentid, bookIndent.getBookindentid()));
            Integer payM = backList.get(i).getBookmoney() * backList.get(i).getNumber();
            if (money != null) {
                money.setType("2");
                moneyService.updateMoney(money);
                //退款
                User user = userService.findByName(getCurrentUser().getUsername());
                user.setMoney(user.getMoney() + payM);
                userService.updateMoney(user);
            }
            WareBook.wareBookChange(bookIndent.getBookname(), "增加", bookIndent.getNumber());
            WarehouseBook warehouseBookServiceOne = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                    .eq(WarehouseBook::getBookname, backList.get(i).getBookname()).eq(WarehouseBook::getPutaway, "1"));
            if (warehouseBookServiceOne == null) {
                bookStoreService.remove(new QueryWrapper<BookStore>().lambda()
                        .eq(BookStore::getBookname, backList.get(i).getBookname()).notIn(BookStore::getFlag, "1"));
                bookSellService.remove(new QueryWrapper<BookSell>().lambda().eq(BookSell::getBookname, backList.get(i).getBookname()));
            }
            //因为不是售书，这里直接删除，不入统计
            bookIndentService.removeById(backList.get(i).getIndentid());
            backList.get(i).setStatus("1");
            backService.backUpdate(backList.get(i));
        }
        return new FebsResponse().success();
    }

    @Log("退书报损-驳回")
    @PostMapping("back/no/{id}")
    @ResponseBody
    @RequiresPermissions("back:no")
    @ControllerEndpoint(operation = "成功驳回", exceptionMessage = "驳回失败")
    public FebsResponse backNo(@PathVariable String id) {
        Back back = backService.getById(id);
        if ("1".equals(back.getStatus())) {
            return new FebsResponse().message("该条报损申请，已通过，不能进行驳回！");
        }
        if ("2".equals(back.getStatus())) {
            return new FebsResponse().message("该条报损申请，已被驳回，请勿重复操作！");
        }
        back.setStatus("2");
        backService.backUpdate(back);
        QueryWrapper<BreakageStat> breakageStatQueryWrapper = new QueryWrapper<>();
        breakageStatQueryWrapper.eq("breakageid", back.getIndentid());
        BreakageStat breakageStat = breakageStatService.getOne(breakageStatQueryWrapper);
        //避免手动添加，出现空指针异常
        if (breakageStat != null) {
            breakageStatService.removeById(breakageStat.getId());
        }
        BookIndent bookIndent = bookIndentService.getById(back.getIndentid());
        //避免手动添加，出现空指针异常
        if (bookIndent != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            String finish = format.format(calendar.getTime());
            bookIndent.setFlag("1").setBackstatus("2").setFinishtime(finish);
            bookIndentService.updateBookIndent(bookIndent);
        }
        return new FebsResponse().success();
    }
}
